package com.rc.saas.tenant.controller.battery;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.controller.elec.ElecPileController;
import com.rc.saas.tenant.model.battery.BatteryOrderSimpleNotify;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.order.OrderInfo;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.elec.PileOfflineSearch;
import com.rc.saas.tenant.service.battery.BatteryOrderSimpleNotifyService;
import com.rc.saas.tenant.service.battery.BatterySimpleReportDetailsService;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.order.OrderInfoService;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.battery.BatterySimpleReportDetailsVo;
import com.rc.saas.tenant.vo.battery.BatteryTotalDataRequestVo;
import com.rc.saas.tenant.vo.battery.BatteryTotalDataRespVo;
import com.rc.saas.tenant.vo.battery.BatteryTotalDataVo;
import com.rc.saas.tenant.vo.elec.PileOfflineVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Member;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author zcg
 * @Date: 2021/4/9 10:07
 */
@Controller
@RequestMapping("/battery")
public class BatteryContorller extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(BatteryContorller.class);

    @Autowired
    private BatteryOrderSimpleNotifyService batteryOrderSimpleNotifyService;
    @Autowired
    private BatterySimpleReportDetailsService batterySimpleReportDetailsService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private MemberInfoService memberInfoService;

    /**
     * 获取电池检测
     * 数量总数，平均得分，存在问题数量
     * 分页数据
     *
     * @return
     */
    @RequestMapping(value = "/listPageByBatteryTotalDataRequestVo", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageByBatteryTotalDataRequestVo(BatteryTotalDataRequestVo batteryTotalDataRequestVo) {
        TenantUser tenantUser=getSessionTenantUser();
        batteryTotalDataRequestVo.setTenantCode(tenantUser.getTenantCode());
        //BatteryTotalDataVo batteryTotalDataVo = batteryOrderSimpleNotifyService.countByBatteryTotalDataRequestVo(batteryTotalDataRequestVo);
        PageInfo<BatteryOrderSimpleNotify> pageInfo = batteryOrderSimpleNotifyService.listPageByBatteryTotalDataRequestVo(batteryTotalDataRequestVo);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 获取电池检测
     * 数量总数，平均得分，存在问题数量
     *
     * @return
     */
    @RequestMapping(value = "/getSumData", method = RequestMethod.GET)
    @ResponseBody
    public TResponse getSumData(BatteryTotalDataRequestVo batteryTotalDataRequestVo) {
        TenantUser tenantUser=getSessionTenantUser();
        batteryTotalDataRequestVo.setTenantCode(tenantUser.getTenantCode());
        BatteryTotalDataVo batteryTotalDataVo = batteryOrderSimpleNotifyService.countByBatteryTotalDataRequestVo(batteryTotalDataRequestVo);
        //Page<BatteryOrderSimpleNotify> page = batteryOrderSimpleNotifyService.listByBatteryTotalDataRequestVo(batteryTotalDataRequestVo, pageNum, pageSize);
        //batteryTotalDataVo.setPage(page);
        return TResponse.SUCCESS_DATA(batteryTotalDataVo);
    }

    /**
     * 跳转电池检测页面
     *
     * @return
     */
    @RequestMapping(value = "/batteryTotalData", method = RequestMethod.GET)
    public String batteryTotalData(Model model) {
        return "/templates/battery/batteryTotalData";
    }


    /**
     * 导出数据
     */
    @ResponseBody
    @RequestMapping("/exportBatteryTotalData")
    public TResponse exportBatteryTotalData(BatteryTotalDataRequestVo batteryTotalDataRequestVo, HttpServletResponse response) {

        if (batteryTotalDataRequestVo.getCount() > 150000) {
            return TResponse.FAIL("最多导出15万数据");
        }
        //导出拼接开始条数
        //导出拼接开始条数
        TenantUser tenantUser=getSessionTenantUser();
        batteryTotalDataRequestVo.setTenantCode(tenantUser.getTenantCode());
        ExportUtils.setDefaultPaging(batteryTotalDataRequestVo);
        List<BatteryOrderSimpleNotify> batteryOrderSimpleNotifies = batteryOrderSimpleNotifyService.listByBatteryTotalDataRequestVo(batteryTotalDataRequestVo);
        List<BatteryTotalDataRespVo> list = JSON.parseArray(JSON.toJSONString(batteryOrderSimpleNotifies), BatteryTotalDataRespVo.class);
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");


        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("电池检测数据", "UTF-8");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + fileName+"_"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) +
                    ".xlsx");
            EasyExcel.write(response.getOutputStream(), BatteryTotalDataRespVo.class).sheet("电池检测数据").doWrite(list);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出电池检测数据失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }


    @ResponseBody
    @RequestMapping(value = "/getSimpleReport", method = RequestMethod.GET)
        public TResponse  getSimpleReport(String outOrderNum){
            if(StringUtils.isBlank(outOrderNum)){
                return TResponse.FAIL("参数为空");
            }
            BatterySimpleReportDetailsVo data=batterySimpleReportDetailsService.listBatterySimpleReportDetailsVoByOutOrderNum(outOrderNum);

        OrderInfo orderInfo=orderInfoService.selectOrderInfoByOutOrderNum(outOrderNum);
        MemberInfo memberInfo=memberInfoService.selectByPrimaryKey(orderInfo.getMemberId());

        HashMap<String,Object> map=new HashMap<>();
        map.put("nickname",memberInfo.getNickname2());
        map.put("mobile",memberInfo.getMobile());
        map.put("getSimpleReportData",data);


        return TResponse.SUCCESS_DATA(map);
    }

}
